package org.amphiprion.kidcalendar.entity;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Period implements Comparable<Period> {
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("E dd MMM yyyy");
	private Date from;
	private Date to;
	private Rule associatedRule;

	public enum PeriodType {
		WEEKEND, VACATION, OTHER
	}

	private PeriodType type;

	public Period() {
	}

	public Period(Rule associatedRule, PeriodType type) {
		this.associatedRule = associatedRule;
		this.type = type;
	}

	public Period(Date from, Date to) {
		this(from, to, null, PeriodType.OTHER);
	}

	public Period(Date from, Date to, Rule associatedRule, PeriodType type) {
		this.from = from;
		this.to = to;
		this.associatedRule = associatedRule;
		this.type = type;
	}

	public PeriodType getType() {
		return type;
	}

	public void setType(PeriodType type) {
		this.type = type;
	}

	public Date getFrom() {
		return from;
	}

	public void setFrom(Date from) {
		this.from = from;
	}

	public Date getTo() {
		return to;
	}

	public void setTo(Date to) {
		this.to = to;
	}

	public Rule getAssociatedRule() {
		return associatedRule;
	}

	public void setAssociatedRule(Rule associatedRule) {
		this.associatedRule = associatedRule;
	}

	public int getNumberOfDays() {
		return 1 + (int) ((to.getTime() - from.getTime()) / 86400000);
	}

	public Period intersec(Period other) {
		Period p = new Period();
		if (from.before(other.from)) {
			p.setFrom(other.from);
		} else {
			p.setFrom(from);
		}

		if (to.after(other.to)) {
			p.setTo(other.to);
		} else {
			p.setTo(to);
		}
		return p;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (from == null ? 0 : from.hashCode());
		result = prime * result + (to == null ? 0 : to.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		Period other = (Period) obj;
		if (from == null) {
			if (other.from != null) {
				return false;
			}
		} else if (!from.equals(other.from)) {
			return false;
		}
		if (to == null) {
			if (other.to != null) {
				return false;
			}
		} else if (!to.equals(other.to)) {
			return false;
		}
		return true;
	}

	@Override
	public int compareTo(Period other) {
		return from.compareTo(other.from);
	}

	@Override
	public String toString() {
		return dateFormat.format(from) + " - " + dateFormat.format(to);
	}

	public void debug() {
		System.out.println("FROM=" + from + " ms=" + from.getTime());
		System.out.println("TO=" + to + " ms=" + to.getTime());
	}
}
